import Foundation

class GeocodingConfig: ObservableObject {
    static let shared = GeocodingConfig()
    
    // MARK: - 服务配置（按解析顺位）
    @Published var primaryService: GeocodingService = .apple      // 1. 苹果本地解析
    @Published var secondaryService: GeocodingService = .amap     // 2. 高德地图解析
    @Published var tertiaryService: GeocodingService = .google    // 3. Google解析
    @Published var quaternaryService: GeocodingService = .openStreetMap // 4. OpenStreetMap解析
    
    // MARK: - 服务启用状态
    @Published var appleEnabled: Bool = true
    @Published var googleEnabled: Bool = true
    @Published var amapEnabled: Bool = true
    @Published var openStreetMapEnabled: Bool = true
    @Published var tencentEnabled: Bool = true
    
    // MARK: - 重试配置
    @Published var maxRetries: Int = 2
    @Published var retryDelay: Double = 1.0
    
    // MARK: - API密钥配置
    @Published var googleApiKey: String = "AIzaSyCfBUsmHsR45yBQnP7rthE70GK-iiKehGo"
    @Published var amapApiKey: String = "237cf159164867ded9990aafc93408ca"
    @Published var tencentApiKey: String = "L5OBZ-2SPON-MCNFK-S63PP-ZJWIV-CTBL4"
    @Published var tencentSecretKey: String = "52tEmYw2osLQnVGECy3GES7zivNlokWm"
    
    private let userDefaults = UserDefaults.standard
    private let configKey = "GeocodingConfig"
    
    private init() {
        loadConfig()
    }
    
    // MARK: - 配置管理
    func saveConfig() {
        let config: [String: Any] = [
            "primaryService": primaryService.rawValue,
            "secondaryService": secondaryService.rawValue,
            "tertiaryService": tertiaryService.rawValue,
            "quaternaryService": quaternaryService.rawValue,
            "appleEnabled": appleEnabled,
            "googleEnabled": googleEnabled,
            "amapEnabled": amapEnabled,
            "openStreetMapEnabled": openStreetMapEnabled,
            "tencentEnabled": tencentEnabled,
            "maxRetries": maxRetries,
            "retryDelay": retryDelay,
            "googleApiKey": googleApiKey,
            "amapApiKey": amapApiKey,
            "tencentApiKey": tencentApiKey,
            "tencentSecretKey": tencentSecretKey
        ]
        
        userDefaults.set(config, forKey: configKey)
        print("📋 地理编码配置已保存")
    }
    
    func loadConfig() {
        guard let config = userDefaults.dictionary(forKey: configKey) else {
            print("📋 使用默认地理编码配置")
            return
        }
        
        primaryService = GeocodingService(rawValue: config["primaryService"] as? String ?? "apple") ?? .apple
        secondaryService = GeocodingService(rawValue: config["secondaryService"] as? String ?? "amap") ?? .amap
        tertiaryService = GeocodingService(rawValue: config["tertiaryService"] as? String ?? "google") ?? .google
        quaternaryService = GeocodingService(rawValue: config["quaternaryService"] as? String ?? "openStreetMap") ?? .openStreetMap
        
        appleEnabled = config["appleEnabled"] as? Bool ?? true
        googleEnabled = config["googleEnabled"] as? Bool ?? true
        amapEnabled = config["amapEnabled"] as? Bool ?? true
        openStreetMapEnabled = config["openStreetMapEnabled"] as? Bool ?? true
        tencentEnabled = config["tencentEnabled"] as? Bool ?? true
        
        maxRetries = config["maxRetries"] as? Int ?? 2
        retryDelay = config["retryDelay"] as? Double ?? 1.0
        
        googleApiKey = config["googleApiKey"] as? String ?? "AIzaSyCfBUsmHsR45yBQnP7rthE70GK-iiKehGo"
        amapApiKey = config["amapApiKey"] as? String ?? "237cf159164867ded9990aafc93408ca"
        tencentApiKey = config["tencentApiKey"] as? String ?? "L5OBZ-2SPON-MCNFK-S63PP-ZJWIV-CTBL4"
        tencentSecretKey = config["tencentSecretKey"] as? String ?? "52tEmYw2osLQnVGECy3GES7zivNlokWm"
        
        print("📋 地理编码配置已加载")
    }
    
    func resetConfig() {
        primaryService = .apple
        secondaryService = .google
        tertiaryService = .amap
        quaternaryService = .openStreetMap
        
        appleEnabled = true
        googleEnabled = true
        amapEnabled = true
        openStreetMapEnabled = true
        tencentEnabled = true
        
        maxRetries = 2
        retryDelay = 1.0
        
        googleApiKey = "AIzaSyCfBUsmHsR45yBQnP7rthE70GK-iiKehGo"
        amapApiKey = "237cf159164867ded9990aafc93408ca"
        tencentApiKey = "L5OBZ-2SPON-MCNFK-S63PP-ZJWIV-CTBL4"
        tencentSecretKey = "52tEmYw2osLQnVGECy3GES7zivNlokWm"
        
        saveConfig()
        print("📋 地理编码配置已重置为默认值")
    }
    
    // MARK: - 获取可用服务列表（按正确优先级）
    func getAvailableServices() -> [GeocodingService] {
        var services: [GeocodingService] = []
        
        // 按照正确的优先级顺序：腾讯 → 高德 → 谷歌 → OpenStreetMap → Apple
        if tencentEnabled { services.append(.tencent) }
        if amapEnabled { services.append(.amap) }
        if googleEnabled { services.append(.google) }
        if openStreetMapEnabled { services.append(.openStreetMap) }
        if appleEnabled { services.append(.apple) }
        
        // 去重并保持优先级顺序
        var uniqueServices: [GeocodingService] = []
        for service in services {
            if !uniqueServices.contains(service) {
                uniqueServices.append(service)
            }
        }
        
        return uniqueServices
    }
    
    // MARK: - 验证配置
    func validateConfig() -> Bool {
        let availableServices = getAvailableServices()
        
        if availableServices.isEmpty {
            print("❌ 地理编码配置错误: 没有启用任何服务")
            return false
        }
        
        if googleEnabled && (googleApiKey.isEmpty || googleApiKey == "YOUR_GOOGLE_MAPS_API_KEY") {
            print("⚠️ 地理编码配置警告: Google Maps API密钥未设置")
        }
        
        if tencentEnabled && (tencentApiKey.isEmpty || tencentSecretKey.isEmpty) {
            print("⚠️ 地理编码配置警告: 腾讯地图API密钥或签名密钥未设置")
        }
        
        print("✅ 地理编码配置验证通过: 可用服务 \(availableServices.count) 个")
        return true
    }
}

// MARK: - 地理编码服务枚举
enum GeocodingService: String, CaseIterable {
    case apple = "apple"
    case google = "google"
    case amap = "amap"
    case openStreetMap = "openStreetMap"
    case tencent = "tencent"
    
    var displayName: String {
        switch self {
        case .apple:
            return "Apple CoreLocation"
        case .google:
            return "Google Maps API"
        case .amap:
            return "高德地图API"
        case .openStreetMap:
            return "OpenStreetMap Nominatim"
        case .tencent:
            return "腾讯地图API"
        }
    }
    
    var description: String {
        switch self {
        case .apple:
            return "本地服务，免费，海外覆盖有限"
        case .google:
            return "全球覆盖，需要API密钥，有配额限制"
        case .amap:
            return "中国地区覆盖好，免费"
        case .openStreetMap:
            return "全球覆盖，免费，响应较慢"
        case .tencent:
            return "中国地区覆盖好，需要签名验证"
        }
    }
} 